﻿using AutoMapper;
using BackData;
using Domain.DTOs.Equipmentes;
using Domain.Quality;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.Equipment;

namespace Team.API.Applocation.Hanldler.Equipment
{
    /// <summary>
    /// 处理获取设备列表的命令处理器
    /// 实现MediatR的IRequestHandler接口，用于处理GetEquipmentListCommand并返回包含EquipmentDTO列表的APIResult
    /// </summary>
    public class GetEquipmentListHandler : IRequestHandler<GetEquipmentListCommand, APIResult<List<EquipmentDTO>>>
    {
        private readonly IMapper mapper;
        private readonly IRepository<Equipmentmodel> equiRep;
        /// <summary>
        /// 构造函数，注入AutoMapper的IMapper和设备仓储IRepository<EquipmentModel>
        /// </summary>
        /// <param name="mapper">用于对象映射的AutoMapper实例</param>
        /// <param name="equiRep">设备领域模型的仓储实例，用于数据查询</param>
        public GetEquipmentListHandler(IMapper mapper,IRepository<Equipmentmodel> equiRep)
        {
            this.mapper = mapper;
            this.equiRep = equiRep;
        }
        /// <summary>
        /// 处理获取设备列表的核心方法
        /// 异步执行设备查询，筛选未删除的设备，再映射为DTO并封装成APIResult返回
        /// </summary>
        /// <param name="request">获取设备列表的命令对象，无额外参数（若有分页、筛选等可在此扩展）</param>
        /// <param name="cancellationToken">用于异步操作取消的令牌</param>
        /// <returns>包含设备DTO列表、状态码和提示信息的APIResult</returns>
        public async Task<APIResult<List<EquipmentDTO>>> Handle(GetEquipmentListCommand request, CancellationToken cancellationToken)
        {
            var list =await equiRep.GetAll().Where(x => !x.IsDel).ToListAsync(); // 先执行查询获取实体列表
            if(!string.IsNullOrEmpty(request.Manager))
            {
                list=list.Where(x => x.Manager.Contains(request.Manager)).ToList();
            }
            var resultDTOs = mapper.Map<List<EquipmentDTO>>(list); // 再映射为DTO列表
            return new APIResult<List<EquipmentDTO>>
            {
                Code = StateCode.OK,
                Message = "设备查询成功",
                Result = resultDTOs
            };
        }
    }
}
